﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System.IO;

namespace TestTcpSockets.Xml
{
    [XmlRoot("iq")]
    public class IQ
    {
        [XmlAttribute("type")]
        public string IqType { get; set; }

        [XmlAttribute("id")]
        public int Identifier { get; set; }

        [XmlAttribute("from")]
        public string From { get; set; }

        [XmlAttribute("to")]
        public string To { get; set; }

        [XmlElement("query")]
        public Query Content { get; set; }

        [XmlElement("bind")]
        public Bind Binding { get; set; }

        public string Serialize()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(IQ));
            using (MemoryStream memStream = new MemoryStream())
            {
                using (XmlTextWriter xmlWriter = new XmlTextWriter(memStream, Encoding.UTF8))
                {
                    xmlWriter.Settings.OmitXmlDeclaration = true;
                    serializer.Serialize(xmlWriter, this);
                    xmlWriter.Close();
                }
                memStream.Close();

                string xml = Encoding.UTF8.GetString(memStream.GetBuffer());
                xml = xml.Substring(xml.IndexOf(Convert.ToChar(60)));
                xml = xml.Substring(0, (xml.LastIndexOf(Convert.ToChar(62)) + 1));
                return xml;
            }
        }

        public static IQ Deserialize(string xmlData)
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof (IQ));
                using (StringReader stringReader = new StringReader(xmlData))
                {
                    using (XmlTextReader xmlReader = new XmlTextReader(stringReader))
                    {
                        return (IQ) serializer.Deserialize(xmlReader);
                    }
                }
            } catch (Exception ex)
            {
                return null;
            }
        }
    }
}
